<template>
  <n-card title="AI Agent管理">
    <n-space vertical>
      <!-- 全局应用提示 -->
      <n-alert type="info" v-if="globalAgent">
        当前全局应用: <strong>{{ globalAgent.name }}</strong> -
        {{ globalAgent.description }}
        <template #action>
          <n-button text @click="clearGlobalAgent" type="primary"
            >取消应用</n-button
          >
        </template>
      </n-alert>

      <!-- 操作栏 -->
      <div class="action-bar">
        <n-space>
          <n-button type="primary" @click="showCreateModal = true">
            <template #icon>
              <n-icon><AddOutline /></n-icon>
            </template>
            新建Agent
          </n-button>
          <n-button @click="refreshAgents">
            <template #icon>
              <n-icon><RefreshOutline /></n-icon>
            </template>
            刷新
          </n-button>
        </n-space>

        <n-space>
          <n-input
            v-model:value="searchKeyword"
            placeholder="搜索Agent名称..."
            style="width: 200px"
            clearable
          />
        </n-space>
      </div>

      <!-- Agent列表 -->
      <n-data-table
        :columns="columns"
        :data="filteredAgents"
        :bordered="false"
        :pagination="pagination"
      />

      <!-- 创建/编辑Agent模态框 -->
      <n-modal v-model:show="showCreateModal" :mask-closable="false">
        <n-card
          style="width: 800px; max-width: 95vw"
          :title="editingAgent ? '编辑AI Agent' : '新建AI Agent'"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <template #header-extra>
            <n-button quaternary circle @click="showCreateModal = false">
              <template #icon>
                <n-icon><CloseOutline /></n-icon>
              </template>
            </n-button>
          </template>

          <n-form
            ref="formRef"
            :model="agentForm"
            :rules="rules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            class="agent-form"
          >
            <!-- 基础信息 -->
            <n-divider title-placement="left">基础信息</n-divider>
            <n-grid :cols="2" :x-gap="24">
              <n-gi>
                <n-form-item label="Agent名称" path="name">
                  <n-input
                    v-model:value="agentForm.name"
                    placeholder="请输入Agent名称"
                  />
                </n-form-item>
              </n-gi>
              <n-gi>
                <n-form-item label="Agent类型" path="type">
                  <n-select
                    v-model:value="agentForm.type"
                    :options="agentTypeOptions"
                    placeholder="请选择Agent类型"
                  />
                </n-form-item>
              </n-gi>
            </n-grid>

            <n-form-item label="描述" path="description">
              <n-input
                v-model:value="agentForm.description"
                type="textarea"
                placeholder="请输入Agent描述"
                :rows="2"
              />
            </n-form-item>

            <!-- API配置 -->
            <n-divider title-placement="left">API配置</n-divider>
            <n-grid :cols="2" :x-gap="12">
              <n-gi>
                <n-form-item label="API密钥" path="apiConfig.apiKey">
                  <n-input
                    v-model:value="agentForm.apiConfig.apiKey"
                    placeholder="请输入API密钥"
                    type="password"
                    show-password-on="click"
                  />
                </n-form-item>
              </n-gi>
              <n-gi>
                <n-form-item label="API地址" path="apiConfig.baseURL">
                  <n-input
                    v-model:value="agentForm.apiConfig.baseURL"
                    placeholder="https://apis.iflow.cn/v1"
                  />
                </n-form-item>
              </n-gi>
            </n-grid>

            <n-grid :cols="2" :x-gap="12">
              <n-gi>
                <n-form-item label="模型" path="baseModel">
                  <n-input
                    v-model:value="agentForm.baseModel"
                    placeholder="请输入模型名称"
                  />
                </n-form-item>
              </n-gi>
              <n-gi>
                <n-form-item label="最大token数" path="apiConfig.max_tokens">
                  <n-input-number
                    v-model:value="agentForm.apiConfig.max_tokens"
                    :min="100"
                    :max="4000"
                    placeholder="1000"
                    style="width: 100%"
                  />
                </n-form-item>
              </n-gi>
            </n-grid>

            <n-form-item>
              <n-button
                @click="testAPIConnection"
                type="primary"
                size="small"
                :loading="testingConnection"
              >
                <template #icon>
                  <n-icon><CheckmarkCircleOutline /></n-icon>
                </template>
                测试连接
              </n-button>
            </n-form-item>

            <!-- 模型参数 -->
            <n-divider title-placement="left">模型参数</n-divider>
            <n-form-item label="温度参数 (Temperature)" path="temperature">
              <n-space vertical style="width: 100%">
                <n-slider
                  v-model:value="agentForm.temperature"
                  :step="0.1"
                  :min="0"
                  :max="2"
                  :format-tooltip="(value: number) => value.toFixed(1)"
                />
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    color: #666;
                    font-size: 12px;
                  "
                >
                  <span>确定性 (0.0)</span>
                  <span>平衡性 (1.0)</span>
                  <span>创造性 (2.0)</span>
                </div>
                <div style="text-align: center; color: #666; margin-top: 8px">
                  当前值: <strong>{{ agentForm.temperature }}</strong>
                  <span
                    v-if="temperatureSuggestions[agentForm.temperature]"
                    style="margin-left: 8px; color: #1890ff"
                  >
                    {{ temperatureSuggestions[agentForm.temperature] }}
                  </span>
                </div>
                <n-alert type="info" size="small" style="margin-top: 8px">
                  <n-space vertical>
                    <div><strong>场景建议:</strong></div>
                    <div>• 代码生成/数学解题: 0.0</div>
                    <div>• 数据抽取/分析: 1.0</div>
                    <div>• 通用对话/翻译: 1.3</div>
                    <div>• 创意写作/诗歌: 1.5</div>
                  </n-space>
                </n-alert>
              </n-space>
            </n-form-item>

            <!-- 提示词配置 -->
            <n-divider title-placement="left">提示词配置</n-divider>
            <n-form-item label="系统提示词" path="systemPrompt">
              <n-input
                v-model:value="agentForm.systemPrompt"
                type="textarea"
                placeholder="请输入系统级提示词，用于设定Agent的角色和行为"
                :rows="4"
              />
            </n-form-item>

            <!-- 规则配置 -->
            <n-divider title-placement="left">规则配置</n-divider>
            <n-form-item label="规则集配置" path="rules">
              <n-dynamic-input
                v-model:value="agentForm.rules"
                :on-create="createRule"
                :min="1"
                #="{ value, index }"
              >
                <div class="rule-item">
                  <n-input
                    v-model:value="value.content"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入规则内容"
                    style="margin-bottom: 12px"
                  />
                  <n-space justify="space-between" align="center">
                    <n-space>
                      <n-select
                        v-model:value="value.priority"
                        :options="priorityOptions"
                        style="width: 120px"
                        placeholder="优先级"
                      />
                      <n-switch v-model:value="value.enabled">
                        <template #checked>启用</template>
                        <template #unchecked>禁用</template>
                      </n-switch>
                    </n-space>
                    <n-button
                      quaternary
                      type="error"
                      size="small"
                      @click="removeRule(index)"
                    >
                      <template #icon>
                        <n-icon><TrashOutline /></n-icon>
                      </template>
                      删除
                    </n-button>
                  </n-space>
                </div>
              </n-dynamic-input>
            </n-form-item>

            <!-- 高级配置 -->
            <n-divider title-placement="left">高级配置</n-divider>
            <n-form-item>
              <n-space vertical>
                <n-checkbox v-model:checked="agentForm.enableMemory"
                  >启用记忆功能</n-checkbox
                >
                <n-checkbox v-model:checked="agentForm.enableTools"
                  >启用工具调用</n-checkbox
                >
                <n-checkbox v-model:checked="agentForm.enableWebSearch"
                  >启用网络搜索</n-checkbox
                >
              </n-space>
            </n-form-item>
          </n-form>

          <template #footer>
            <n-space justify="end">
              <n-button @click="showCreateModal = false">取消</n-button>
              <n-button type="primary" @click="handleSaveAgent">
                {{ editingAgent ? "更新" : "创建" }}
              </n-button>
            </n-space>
          </template>
        </n-card>
      </n-modal>
    </n-space>
  </n-card>
</template>

<script setup>
import { ref, reactive, computed, h } from "vue";
import {
  NCard,
  NSpace,
  NAlert,
  NButton,
  NIcon,
  NDataTable,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSlider,
  NCheckbox,
  NSwitch,
  NGrid,
  NGi,
  NDynamicInput,
  NDivider,
  NInputNumber,
  useMessage,
} from "naive-ui";
import {
  AddOutline,
  RefreshOutline,
  CloseOutline,
  TrashOutline,
  CreateOutline,
  CheckmarkCircleOutline,
  PlayOutline,
} from "@vicons/ionicons5";
import { flowAPI } from "@/utils/api.js";
import {
  API_CONFIG,
  MODEL_CONFIG,
  TEMPERATURE_SUGGESTIONS,
  SCENARIO_TEMPERATURES,
} from "@/config/api.js";

const message = useMessage();

// 温度参数建议
const temperatureSuggestions = {
  0.0: "💻 代码/数学",
  0.5: "📊 数据分析",
  1.0: "⚖️ 平衡模式",
  1.3: "💬 对话/翻译",
  1.5: "🎨 创意写作",
  2.0: "🚀 高创造性",
};

// 数据状态
const globalAgent = ref(null);
const agents = ref([
  {
    id: "1",
    name: "试飞大纲专家",
    type: "specialist",
    description: "专门用于生成试飞大纲的专家Agent",
    baseModel: "", // 留空，您之后可以固定填写
    temperature: 1.0, // 默认改为1.0
    status: "active",
    createdTime: "2025-10-20",
    usageCount: 156,
    apiConfig: {
      provider: "iflow",
      apiKey: "",
      baseURL: "https://apis.iflow.cn/v1",
      max_tokens: 1000,
    },
  },
  {
    id: "2",
    name: "数据分析助手",
    type: "analyst",
    description: "用于数据分析和报表生成的Agent",
    baseModel: "", // 留空，您之后可以固定填写
    temperature: 1.0, // 默认改为1.0
    status: "active",
    createdTime: "2025-10-20",
    usageCount: 89,
    apiConfig: {
      provider: "iflow",
      apiKey: "",
      baseURL: "https://apis.iflow.cn/v1",
      max_tokens: 1000,
    },
  },
  {
    id: "3",
    name: "智能电缆搭建专家",
    type: "engineer",
    description: "专门负责电缆布线规划、线缆选型、连接方案设计的工程专家",
    baseModel: "deepseek-v3.2", // 留空，您之后可以固定填写glm-4.6 qwen3-coder deepseek-v3.2
    temperature: 1.0, // 默认改为1.0
    status: "active",
    createdTime: "2025-10-20",
    usageCount: 42,
    systemPrompt: `你是一个专业的飞机电缆系统工程师，专门负责飞机电缆系统的设计、规划和优化。你精通各种电缆规格、布线标准、电磁兼容性要求和航空安全规范。具备完整的飞机系统知识，包括电源系统、数据总线、通信导航、传感器网络等。`,
    rules: [
      {
        content:
          "必须优先考虑航空级标准和适航要求，所有设计必须符合DO-160、DO-178、DO-254等航空标准",
        priority: "high",
        enabled: true,
      },
      {
        content:
          "可用的电缆系统组件包括：连接器、飞机电源、应急电源、ARINC 429总线、ARINC 664总线、CAN总线、VHF电台、HF电台、卫星通信、ADIRU、GPS接收机、ILS接收机、大气数据传感器、雷达高度表、EFIS显示器、FMS、EICAS、音频面板、机载摄像头、EMI滤波器、雷击保护器、军标连接器、光纤连接器等航空专用设备。生成拓扑时必须使用这些组件类型。",
        priority: "high",
        enabled: true,
      },
      {
        content: "电源系统设计必须采用双冗余或三冗余架构，确保系统可靠性",
        priority: "high",
        enabled: true,
      },
      {
        content:
          "电缆选型必须考虑工作环境：耐高温、阻燃、防潮、抗振动、防电磁干扰",
        priority: "high",
        enabled: true,
      },
      {
        content:
          "数据总线必须正确匹配：ARINC 429用于航电系统，ARINC 664用于AFDX网络，CAN总线用于子系统控制",
        priority: "high",
        enabled: true,
      },
      {
        content:
          "高低压电缆必须分开布线，电源线与信号线保持最小间距30cm，交叉时成90度角",
        priority: "high",
        enabled: true,
      },
      {
        content:
          "所有连接器必须选用航空级标准件，如MIL-DTL-38999系列，并考虑防误插设计",
        priority: "high",
        enabled: true,
      },
      {
        content:
          "必须为关键系统（如飞行控制、发动机控制）提供独立的电缆路径和备份线路",
        priority: "high",
        enabled: true,
      },
      {
        content: "电缆屏蔽必须完整可靠，屏蔽层单点接地，防止地环路干扰",
        priority: "medium",
        enabled: true,
      },
      {
        content: "考虑电缆重量优化，在满足性能前提下选择轻量化电缆和连接器",
        priority: "medium",
        enabled: true,
      },
      {
        content: "布线路径必须避开高温区、运动部件、燃油管路等危险区域",
        priority: "medium",
        enabled: true,
      },
      {
        content: "电缆弯曲半径必须符合标准：动力电缆≥8倍外径，信号电缆≥6倍外径",
        priority: "medium",
        enabled: true,
      },
      {
        content: "必须考虑维护性：提供足够的测试点、连接器操作空间、电缆标识",
        priority: "medium",
        enabled: true,
      },
      {
        content: "通信系统电缆必须考虑阻抗匹配，射频电缆使用同轴电缆并正确端接",
        priority: "medium",
        enabled: true,
      },
      {
        content: "传感器电缆必须采用双绞线或屏蔽双绞线，减少共模干扰",
        priority: "medium",
        enabled: true,
      },
      {
        content: "光纤电缆用于高速数据传输，必须考虑弯曲半径和连接器清洁",
        priority: "medium",
        enabled: true,
      },
      {
        content:
          "必须提供完整的电缆清单：包括电缆型号、长度、连接器类型、引脚定义",
        priority: "low",
        enabled: true,
      },
      {
        content: "考虑未来扩展性，预留10-20%的备用线缆和连接器端口",
        priority: "low",
        enabled: true,
      },
      {
        content:
          "电缆标识必须清晰：使用航空级标签，包含电缆编号、起止设备、信号类型",
        priority: "low",
        enabled: true,
      },
    ],
    enableMemory: true,
    enableTools: true,
    enableWebSearch: false,
    apiConfig: {
      provider: "iflow",
      apiKey: "sk-a79d345d26d869e4e7c8f8c5b2dd9961",
      baseURL: "https://apis.iflow.cn/v1/chat/completions",
      max_tokens: 1000,
    },
  },
]);

// 搜索和分页
const searchKeyword = ref("");
const pagination = ref({ pageSize: 10 });

// 模态框状态
const showCreateModal = ref(false);
const editingAgent = ref(null);
const testingConnection = ref(false);

// 表单数据
const agentForm = reactive({
  name: "",
  type: "",
  description: "",
  baseModel: API_CONFIG.IFLOW.DEFAULT_MODEL,
  temperature: API_CONFIG.IFLOW.DEFAULT_TEMPERATURE,
  systemPrompt: "",
  rules: [],
  enableMemory: true,
  enableTools: false,
  enableWebSearch: false,
  // API 配置
  apiConfig: {
    provider: "iflow",
    apiKey: "",
    baseURL: API_CONFIG.IFLOW.BASE_URL,
    max_tokens: API_CONFIG.IFLOW.DEFAULT_MAX_TOKENS,
  },
});

// 选项数据
const agentTypeOptions = [
  { label: "专家型", value: "specialist" },
  { label: "分析型", value: "analyst" },
  { label: "创意型", value: "creative" },
  { label: "严谨型", value: "strict" },
];

const priorityOptions = [
  { label: "高", value: "high" },
  { label: "中", value: "medium" },
  { label: "低", value: "low" },
];

// 计算属性
const filteredAgents = computed(() => {
  if (!searchKeyword.value) return agents.value;
  return agents.value.filter(
    (agent) =>
      agent.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      agent.description
        .toLowerCase()
        .includes(searchKeyword.value.toLowerCase())
  );
});

// 表格列定义
const columns = [
  {
    title: "Agent名称",
    key: "name",
    render: (row) => h("div", { style: "font-weight: 500;" }, row.name),
  },
  {
    title: "类型",
    key: "type",
    render: (row) => {
      const typeMap = {
        specialist: "专家型",
        analyst: "分析型",
        creative: "创意型",
        strict: "严谨型",
      };
      return typeMap[row.type] || row.type;
    },
  },
  {
    title: "描述",
    key: "description",
    ellipsis: { tooltip: true },
  },
  {
    title: "模型",
    key: "baseModel",
    render: (row) => {
      return h(
        "n-tag",
        {
          size: "small",
          type: row.baseModel ? "info" : "warning",
        },
        {
          default: () => row.baseModel || "未设置",
        }
      );
    },
  },
  {
    title: "温度",
    key: "temperature",
    render: (row) => {
      const suggestion = temperatureSuggestions[row.temperature] || "";
      return h("div", [
        h("span", { style: "margin-right: 8px;" }, row.temperature),
        h(
          "n-tag",
          {
            size: "small",
            type: "info",
            bordered: false,
          },
          {
            default: () => suggestion,
          }
        ),
      ]);
    },
  },
  {
    title: "使用次数",
    key: "usageCount",
    render: (row) =>
      h("n-tag", { size: "small" }, { default: () => row.usageCount }),
  },
  {
    title: "操作",
    key: "actions",
    render: (row) =>
      h(
        NSpace,
        { size: "small" },
        {
          default: () => [
            h(
              NButton,
              {
                size: "small",
                type: row.id === globalAgent.value?.id ? "primary" : "default",
                onClick: () => applyGlobalAgent(row),
              },
              {
                default: () =>
                  row.id === globalAgent.value?.id ? "已应用" : "全局应用",
              }
            ),
            h(
              NButton,
              {
                size: "small",
                onClick: () => editAgent(row),
              },
              {
                default: () => "编辑",
                icon: () => h(NIcon, null, { default: () => h(CreateOutline) }),
              }
            ),
            h(
              NButton,
              {
                size: "small",
                type: "primary",
                onClick: () => testAgent(row),
              },
              {
                default: () => "测试",
                icon: () => h(NIcon, null, { default: () => h(PlayOutline) }),
              }
            ),
          ],
        }
      ),
  },
];

// 表单规则
const rules = {
  name: { required: true, message: "请输入Agent名称", trigger: "blur" },
  type: { required: true, message: "请选择Agent类型", trigger: "change" },
  baseModel: { required: true, message: "请输入模型名称", trigger: "blur" },
  "apiConfig.apiKey": {
    required: true,
    message: "请输入API密钥",
    trigger: "blur",
  },
  "apiConfig.baseURL": {
    required: true,
    message: "请输入API地址",
    trigger: "blur",
  },
};

// 方法
const createRule = () => ({
  content: "",
  priority: "medium",
  enabled: true,
});

const removeRule = (index) => {
  agentForm.rules.splice(index, 1);
};

const testAPIConnection = async () => {
  if (!agentForm.apiConfig.apiKey) {
    message.warning("请输入API密钥");
    return;
  }

  if (!agentForm.apiConfig.baseURL) {
    message.warning("请输入API地址");
    return;
  }

  if (!agentForm.baseModel) {
    message.warning("请输入模型名称");
    return;
  }

  testingConnection.value = true;
  try {
    const success = await flowAPI.testConnection(
      agentForm.apiConfig.apiKey,
      agentForm.baseModel,
      agentForm.apiConfig.baseURL // 传递自定义API地址
    );
    if (success) {
      message.success("API连接测试成功！");
    } else {
      message.error("API连接测试失败，请检查配置");
    }
  } catch (error) {
    message.error("连接测试异常: " + error.message);
  } finally {
    testingConnection.value = false;
  }
};

const applyGlobalAgent = (agent) => {
  globalAgent.value = agent;
  message.success(`已全局应用Agent: ${agent.name}`);
  localStorage.setItem("globalAgent", JSON.stringify(agent));
};

const clearGlobalAgent = () => {
  globalAgent.value = null;
  localStorage.removeItem("globalAgent");
  message.info("已取消全局应用");
};

const editAgent = (agent) => {
  editingAgent.value = agent;
  Object.assign(agentForm, {
    ...agent,
    rules: agent.rules || [createRule()],
    apiConfig: agent.apiConfig || {
      provider: "iflow",
      apiKey: "",
      baseURL: "https://apis.iflow.cn/v1",
      max_tokens: 1000,
    },
  });
  showCreateModal.value = true;
};

const testAgent = (agent) => {
  message.info(`测试Agent: ${agent.name}`);
  // 这里可以跳转到测试页面或打开测试对话框
};

const handleSaveAgent = () => {
  // 表单验证和保存逻辑
  if (editingAgent.value) {
    // 更新现有Agent
    const index = agents.value.findIndex((a) => a.id === editingAgent.value.id);
    if (index !== -1) {
      agents.value[index] = { ...agentForm, id: editingAgent.value.id };
    }
    message.success("Agent更新成功");
  } else {
    // 创建新Agent
    const newAgent = {
      ...agentForm,
      id: Date.now().toString(),
      status: "active",
      createdTime: new Date().toISOString().split("T")[0],
      usageCount: 0,
    };
    agents.value.push(newAgent);
    message.success("Agent创建成功");
  }

  showCreateModal.value = false;
  resetForm();
};

const refreshAgents = () => {
  message.info("刷新Agent列表");
  // 这里可以调用API重新加载数据
};

const resetForm = () => {
  editingAgent.value = null;
  Object.assign(agentForm, {
    name: "",
    type: "",
    description: "",
    baseModel: "",
    temperature: 1.0, // 重置为1.0
    systemPrompt: "",
    rules: [createRule()],
    enableMemory: true,
    enableTools: false,
    enableWebSearch: false,
    apiConfig: {
      provider: "iflow",
      apiKey: "",
      baseURL: "https://apis.iflow.cn/v1",
      max_tokens: 1000,
    },
  });
};

// 初始化
const init = () => {
  const savedAgent = localStorage.getItem("globalAgent");
  if (savedAgent) {
    globalAgent.value = JSON.parse(savedAgent);
  } else if (agents.value.length > 0) {
    // 如果没有保存的Agent，自动应用第一个Agent
    applyGlobalAgent(agents.value[0]);
  }
  agentForm.rules = [createRule()];
};

init();
</script>

<style scoped>
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

:deep(.n-data-table) {
  margin-top: 16px;
}

:deep(.agent-form .n-form-item) {
  margin-bottom: 20px;
}

:deep(.rule-item) {
  width: 100%;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  margin-bottom: 8px;
}
</style>